package com.kehutong.webchat.util;

import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.coraframework.json.JSONObject;
import org.coraframework.util.secret.Base64Coder;

public class AESUtils {
	
	public static void main(String[] args) throws Exception {
		System.out.println(decrypt("aPVVdptpZafcuwQR1fqXkJq3SqSNyMexX+DRp8fZzMBLvGpfr8lMgSlFcmrYB+wsA36emqKANchWfv+mbE/wlIYIeOI7pK38BHxGT7KrJoMQCiAnZphQrrE0UcUKhZh9B8ttB6Lo+RVBlmvydHejMnB4D7tR2F0kL20dl4A8G6bHFr2OfFjSWEGAPE+A7t6rZ2qZWvROulbxVO4BYm7Hfh3+DCO5jidND7fvBMbSUtCJOs1gQLqYHuNSvWUk4zCEkqDHrYej47ap0Bl0c5DSGdaKB6qVwFFO+0xpNkvnGEj33xOyn0AwBQkesIAiATkSecKTy8esI6YxNVt7fgeeeog5aTiWAhwRDz/m4kakuMRlvSjn1Nr6QKkKSvmtLsfkwTzPgxJw/r+PG4kSjFViLrqZpylAVj9/qWEnNQ4i2uxPUS0AFj+eQ/X74TvQFhRo9LOgX3p374QGbBvImUPaMQ==", 
				"MwDtWAkS0df0lAZm8IXzcQ==",
				"TNVmkDiwz0+wNUR/5P3fxQ=="));
	}

	public static JSONObject decrypt(String encryptedData, String sessionKey, String iv) throws Exception {
		byte[] dataByte = Base64Coder.decode(encryptedData);
		byte[] keyByte = Base64Coder.decode(sessionKey);
		byte[] ivByte = Base64Coder.decode(iv);
		
		
		// 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
		int base = 16;
		if (keyByte.length % base != 0) {
			int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
			byte[] temp = new byte[groups * base];
			Arrays.fill(temp, (byte) 0);
			System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
			keyByte = temp;
		}
		
		Security.addProvider(new BouncyCastleProvider());
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
		SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
		AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
		parameters.init(new IvParameterSpec(ivByte));
		cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
		
		byte[] bytes = cipher.doFinal(dataByte);
		if (bytes != null && bytes.length > 0) {
			String result = new String(bytes, "UTF-8");
			return JSONObject.parseObject(result);
		}
		return null;
	}
	

}